import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import QtQuick.Effects

Item {
id: root
Theme { id: theme }

// ==== 颜色配置（统一管理） ====
property color calendarBackgroundColor: "#FFFFFF"            // 展开背景
property color collapsedBackgroundColor: "#FFFFFF"           // 收起按钮背景
property color collapsedBorderColor: theme.borderColor        // 收起按钮边框
property color collapsedTextColor: "#000000"                 // 收起按钮日期文字
property color collapsedIconColor: "#000000"                 // 收起按钮图标颜色
property color headerTextColor: "#000000"                    // 顶部年月与左右箭头
property color weekdayTextColor: "#000000"                   // 周标题（周一~周日）
property color dayTextColor: "#000000"                       // 当月日期文字
property color dayTextNonCurrentMonthColor: theme.borderColor // 非当月日期文字
property color selectedDayBackgroundColor: "#FFFFFF"         // 选中日期底色
property color selectedDayBorderColor: theme.focusColor       // 选中日期边框色
property int   selectedDayBorderWidth: 2                      // 选中日期边框宽度
property color selectedDayTextColor: "#000000"               // 选中日期文字颜色

// ==== 外部接口 ====
property bool backgroundVisible: true
property real radius: 20
property int padding: 15
property bool shadowEnabled: true
property date selectedDate: new Date()
signal dateClicked(var clickedDate)

property int currentYear: selectedDate.getFullYear()
property int currentMonth: selectedDate.getMonth()
property var dayModel: []
property bool expanded: false       // 控制是否展开显示日历

implicitWidth: 160
implicitHeight: 60

// ==== 生成日历模型 ====
function generateCalendarModel() {
    var tempModel = [],
        date = new Date(currentYear, currentMonth, 1),
        firstDayOfWeek = date.getDay(),
        daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate(),
        daysInPrevMonth = new Date(currentYear, currentMonth, 0).getDate(),
        today = new Date(),
        remaining, isToday, i

    for (i = 0; i < firstDayOfWeek; i++) {
        tempModel.push({
            day: daysInPrevMonth - firstDayOfWeek + 1 + i,
            isCurrentMonth: false,
            isToday: false,
            dateValue: new Date(currentYear, currentMonth - 1, daysInPrevMonth - firstDayOfWeek + 1 + i)
        })
    }

    for (i = 1; i <= daysInMonth; i++) {
        isToday = (currentYear === today.getFullYear() && currentMonth === today.getMonth() && i === today.getDate())
        tempModel.push({
            day: i,
            isCurrentMonth: true,
            isToday: isToday,
            dateValue: new Date(currentYear, currentMonth, i)
        })
    }

    remaining = 42 - tempModel.length
    for (i = 1; i <= remaining; i++) {
        tempModel.push({
            day: i,
            isCurrentMonth: false,
            isToday: false,
            dateValue: new Date(currentYear, currentMonth + 1, i)
        })
    }

    dayModel = tempModel
}

function goToPrevMonth() {
    if (currentMonth > 0) currentMonth--
    else { currentMonth = 11; currentYear-- }
}

function goToNextMonth() {
    if (currentMonth < 11) currentMonth++
    else { currentMonth = 0; currentYear++ }
}

Component.onCompleted: generateCalendarModel()
onCurrentMonthChanged: generateCalendarModel()
onCurrentYearChanged: generateCalendarModel()



Rectangle {
    id: background
    visible: root.backgroundVisible && expanded
    anchors.fill: parent
    radius: root.radius
    color: calendarBackgroundColor
}

// ==== 收起状态 ====
Rectangle {
    id: collapsedButton
    visible: !expanded
    width: 160
    height: 40
    radius: root.radius
    color: collapsedBackgroundColor
    border.color: collapsedBorderColor

    RowLayout {
        anchors.centerIn: parent
        spacing: 8
        Text {
            text: Qt.formatDate(selectedDate, "yyyy-MM-dd")
            color: collapsedTextColor
            font.pixelSize: 18
        }
        Text {
            text: "📅"
            font.pixelSize: 20
            color: collapsedIconColor
        }
    }

    MouseArea {
        anchors.fill: parent
        cursorShape: Qt.PointingHandCursor
        onClicked: {
            calendarPopup.open()
            console.log("[ECalendar] 打开日历选择器")
        }
    }
}

// ==== 弹出选择 ====
Popup {
    id: calendarPopup
    modal: true
    focus: true
    closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
    width: 480
    height: 520
    x: root.window ? (root.window.width - width) / 2 : (root.x + (root.width - width) / 2)
    y: root.window ? (root.window.height - height) / 2 : (root.y + (root.height - height) / 2)
    background: Rectangle {
        color: calendarBackgroundColor
        radius: 16
        border.color: theme.borderColor
    }
    onVisibleChanged: expanded = visible

    contentItem: ColumnLayout {
        anchors.fill: parent
        anchors.margins: root.padding

        RowLayout {
            Layout.fillWidth: true
            Text {
                text: "<"
                font.pixelSize: 24
                color: headerTextColor
                Layout.preferredWidth: 30
                horizontalAlignment: Text.AlignHCenter
                MouseArea { anchors.fill: parent; cursorShape: Qt.PointingHandCursor; onClicked: goToPrevMonth() }
            }

            Text {
                text: currentYear + "年 " + (currentMonth + 1) + "月"
                font.pixelSize: 22
                font.bold: true
                color: headerTextColor
                Layout.fillWidth: true
                horizontalAlignment: Text.AlignHCenter
            }

            Text {
                text: ">"
                font.pixelSize: 24
                color: headerTextColor
                Layout.preferredWidth: 30
                horizontalAlignment: Text.AlignHCenter
                MouseArea { anchors.fill: parent; cursorShape: Qt.PointingHandCursor; onClicked: goToNextMonth() }
            }
        }

        GridLayout {
            columns: 7
            Layout.topMargin: 10
            Layout.fillWidth: true
            Repeater {
                model: ["日", "一", "二", "三", "四", "五", "六"]
                delegate: Text {
                    text: modelData
                    color: weekdayTextColor
                    font.bold: true
                    font.pixelSize: 24
                    horizontalAlignment: Text.AlignHCenter
                    Layout.alignment: Qt.AlignCenter
                    Layout.fillWidth: true
                }
            }
        }

        GridLayout {
            id: dayGrid
            columns: 7
            Layout.topMargin: 5
            Layout.fillWidth: true
            columnSpacing: 4
            rowSpacing: 4

            Repeater {
                model: dayModel
                delegate: Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: (dayGrid.width - (dayGrid.columns - 1) * dayGrid.columnSpacing) / dayGrid.columns
                    Layout.alignment: Qt.AlignCenter
                    radius: width / 2

                    color: {
                        var d1 = modelData.dateValue
                        var d2 = selectedDate
                        if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate())
                            return selectedDayBackgroundColor
                        return "transparent"
                    }

                    border.width: {
                        var d1 = modelData.dateValue
                        var d2 = selectedDate
                        if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate())
                            return selectedDayBorderWidth
                        return 0
                    }
                    border.color: {
                        var d1 = modelData.dateValue
                        var d2 = selectedDate
                        if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate())
                            return selectedDayBorderColor
                        return "transparent"
                    }

                    Text {
                        anchors.centerIn: parent
                        text: modelData.day
                        font.bold: modelData.isToday && modelData.isCurrentMonth
                        font.pixelSize: 22
                        color: {
                            var d1 = modelData.dateValue
                            var d2 = selectedDate
                            if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate())
                                return selectedDayTextColor
                            return modelData.isCurrentMonth ? dayTextColor : dayTextNonCurrentMonthColor
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        cursorShape: Qt.PointingHandCursor
                        onClicked: {
                            var d = modelData.dateValue
                            console.log("[ECalendar] 点击日期:", d.toLocaleDateString(), "完整:", d)
                            selectedDate = d
                            dateClicked(d)
                            calendarPopup.close()
                            expanded = false
                        }
                    }
                }
            }
        }
    }
}

}
